const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'test2_nextjs',
  charset: 'utf8mb4'
};

// 需要添加的子区域数据
const missingAreas = [
  // 许昌(289)的子区域
  { name: '新手村', parent_id: 289, extension: '(1级)' },
  { name: '陈留', parent_id: 289, extension: '(5级)' },
  { name: '九里山', parent_id: 289, extension: '(20级)' },
  { name: '芒砀山', parent_id: 289, extension: '(30级)' },

  // 洛阳(302)的子区域
  { name: '官渡', parent_id: 302, extension: '(40级)' },
  { name: '虎牢关', parent_id: 302, extension: '(50级)' },
  { name: '乌巢', parent_id: 302, extension: '(80级)' },
  { name: '函谷关', parent_id: 302, extension: '(55级)' },

  // 长安(304)的子区域
  { name: '华山', parent_id: 304, extension: '(90级)' },
  { name: '潼关', parent_id: 304, extension: '(75级)' },
  { name: '五丈原', parent_id: 304, extension: '(65级)' },

  // 成都(70)的子区域
  { name: '落凤坡', parent_id: 70, extension: '(30级)' },
  { name: '广汉', parent_id: 70, extension: '(40级)' },
  { name: '峨眉山', parent_id: 70, extension: '(50级)' },

  // 南中(111)的子区域
  { name: '云南', parent_id: 111, extension: '(60级)' },
  { name: '泸水', parent_id: 111, extension: '(70级)' },
  { name: '西洱湖', parent_id: 111, extension: '(80级)' },

  // 汉中(117)的子区域
  { name: '子午谷', parent_id: 117, extension: '(90级)' },
  { name: '街亭', parent_id: 117, extension: '(100级)' },
  { name: '上方谷', parent_id: 117, extension: '(120级)' },

  // 长沙(212)的子区域
  { name: '巴陵', parent_id: 212, extension: '' },
  { name: '洞庭湖', parent_id: 212, extension: '' },
  { name: '湘水', parent_id: 212, extension: '(130级)' },

  // 江陵(264)的子区域
  { name: '麦城', parent_id: 264, extension: '(140级)' },
  { name: '长坂坡', parent_id: 264, extension: '(140级)' },
  { name: '夷陵', parent_id: 264, extension: '' }
];

async function addMissingMapAreas () {
  const connection = await mysql.createConnection(dbConfig);

  try {
    console.log('🔧 开始添加缺失的地图区域数据...\n');

    // 检查表结构
    console.log('📋 检查表结构...');
    const [columns] = await connection.execute('DESCRIBE map_areas');
    console.log('✅ 表结构检查完成\n');

    // 获取当前最大ID
    const [maxIdResult] = await connection.execute('SELECT MAX(id) as maxId FROM map_areas');
    let nextId = (maxIdResult[0].maxId || 0) + 1;
    console.log(`📊 当前最大ID: ${maxIdResult[0].maxId}, 下一个ID将从 ${nextId} 开始\n`);

    // 添加缺失的区域
    let addedCount = 0;
    let skippedCount = 0;

    for (const area of missingAreas) {
      try {
        // 检查是否已存在同名区域
        const [existing] = await connection.execute(
          'SELECT id FROM map_areas WHERE name = ? AND parent_id = ?',
          [area.name, area.parent_id]
        );

        if (existing.length > 0) {
          console.log(`⚠️  跳过已存在的区域: ${area.name} (ID: ${existing[0].id})`);
          skippedCount++;
          continue;
        }

        // 插入新区域
        await connection.execute(
          'INSERT INTO map_areas (id, name, parent_id, extension, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())',
          [nextId, area.name, area.parent_id, area.extension]
        );

        console.log(`✅ 添加区域: ${area.name}${area.extension} (ID: ${nextId}, 父级: ${area.parent_id})`);
        addedCount++;
        nextId++;

      } catch (error) {
        console.error(`❌ 添加区域失败 ${area.name}:`, error.message);
      }
    }

    console.log('\n📊 添加完成统计:');
    console.log(`  新增区域: ${addedCount} 个`);
    console.log(`  跳过区域: ${skippedCount} 个`);
    console.log(`  总计处理: ${addedCount + skippedCount} 个`);

    // 验证添加结果
    console.log('\n🔍 验证添加结果...');
    const [totalCount] = await connection.execute('SELECT COUNT(*) as total FROM map_areas');
    console.log(`  总区域数: ${totalCount[0].total}`);

    const [parentCount] = await connection.execute('SELECT COUNT(*) as total FROM map_areas WHERE parent_id IS NOT NULL');
    console.log(`  有父级区域数: ${parentCount[0].total}`);

    const [extensionCount] = await connection.execute('SELECT COUNT(*) as total FROM map_areas WHERE extension IS NOT NULL AND extension != ""');
    console.log(`  有等级信息区域数: ${extensionCount[0].total}`);

    // 显示一些示例
    console.log('\n📋 新增区域示例:');
    const [newAreas] = await connection.execute(
      'SELECT id, name, parent_id, extension FROM map_areas WHERE parent_id IS NOT NULL ORDER BY parent_id, id LIMIT 10'
    );

    newAreas.forEach(area => {
      const parentInfo = area.parent_id ? `(父级: ${area.parent_id})` : '(顶级)';
      const extensionInfo = area.extension ? ` ${area.extension}` : '';
      console.log(`  ID: ${area.id.toString().padStart(4)} | ${area.name}${extensionInfo} | ${parentInfo}`);
    });

    console.log('\n🎉 地图区域数据添加完成！');

  } catch (error) {
    console.error('❌ 添加地图区域失败:', error);
  } finally {
    await connection.end();
  }
}

// 运行脚本
if (require.main === module) {
  addMissingMapAreas().catch(console.error);
}

module.exports = { addMissingMapAreas }; 